#!/usr/bin/python

import cv2
import numpy as np
import logging, sys

log_format = '%(filename)s,%(lineno)d:%(message)s'
logging.basicConfig(level=logging.DEBUG, format=log_format)

class Image():
	def __init__(self,img,factor):
		self.Param = {}
		self.img = cv2.imread(img)
		assert self.img is not None, "issue when loading image %s " %(img)
		self.gray = cv2.cvtColor(self.img,cv2.COLOR_BGR2GRAY)
		self.Param['factor'] = factor
		
		self.run()

	def run(self):
		self.Param['AllImageRet'] = self.calColor(self.img) + self.calGray(self.gray)
		self.Param['ROIImageRet'] = self.calAllAvg()

	def calColor(self,img):
		b, g, r = img.mean(axis=0).mean(axis=0)
		bg, rg = b/g, r/g
		return [r, g, b, rg, bg]

	def calGray(self,img):
		y = img.mean(axis=0).mean(axis=0)
		return [y]

	def calAllAvg(self):
		factor = self.Param['factor']
		height, width, _ = self.img.shape
		dx, dy = int(height/factor), int(width/factor)
		x, y = range(0,height,dx), range(0,width,dy)
		print x,y,height,width

		ROIImageRet = np.zeros([factor,factor,6])
		print "guoben"
		print self.calGray(self.gray)
		print ROIImageRet[1,2,3]
		for ddx in range(factor):
			for ddy in range(factor):
				ROIImageRet[ddx,ddy,0:5] = self.calColor(self.img[x[ddx]:x[ddx]+dx,y[ddy]:y[ddy]+dy])
				ROIImageRet[ddx,ddy,5] = self.calGray(self.gray[x[ddx]:x[ddx]+dx,y[ddy]:y[ddy]+dy])[0]
		return ROIImageRet



def parseInputPara():
	Parameter = {}
	for entry in sys.argv:
		if entry.startswith('img1='):
			Parameter['img1'] = entry[5:]
		elif entry.startswith('img2='):
			Parameter['img2'] = entry[5:]
		elif entry.startswith('factor='):
			Parameter['factor'] = int(entry[7:])
		else:
			logging.error('input parameter %s is wrong!',entry.upper())

	return Parameter


def compare(img1, img2, factor):
	ret1 = Image(img1, factor).Param
	ret2 = Image(img2, factor).Param

	print "ALl image result as follow"
	A1 = ret1['AllImageRet']
	A2 = ret2['AllImageRet']
	print "image1:", A1
	print "image2:", A2
	print "diff:", (np.array(A1) - np.array(A2))/np.array(A1)

	for x in range(factor):
		for y in range(factor):
			print "roi (%d,%d)" %(x, y)
			A1 = ret1['ROIImageRet'][x,y]
			A2 = ret2['ROIImageRet'][x,y]
			print "image1:", A1
			print "image2:", A2
			print "diff:", (np.array(A1) - np.array(A2))/np.array(A1)


if __name__ == '__main__':
	inPara = parseInputPara()
	inputImage1 = inPara['img1']
	inputImage2 = inPara['img2']
	logging.debug("%s,%s" %(inputImage1, inputImage2))
	if inPara.has_key('factor'):
		compare(inputImage1, inputImage2, inPara['factor'])
	else:
		compare(inputImage1, inputImage2, 5)
